<template>
    <div class="stock-detail">
        <TopTitleExit :title="`${ stock_detail_data.shortName }`" :exit="routerExit"></TopTitleExit>
        <!-- <TopTitleExit :title="`${ stock_detail_data.shortName } - ${ stock_detail_data.name }`" :exit="routerExit"></TopTitleExit> -->
        <div class="body">
            <div class="price-line">
                <div class="price">{{ stock_detail_data.name }}</div>
                <!-- <div class="price">{{ stock_detail_data.price }}</div> -->
                <!-- <div class="price">$198.75</div> -->
                <!-- <div class="change" :style="`color: ${ 2.34 > 0 ? 'var(--positive-number-color)' : 'var(--negative-number-color)' }`">$2.34 (1.19%)</div> -->
                <!-- <div class="volume">Volume: {{ stock_detail_data.volume }}</div> -->
                <!-- <div class="volume">Price: {{ stock_detail_data.price }}</div> -->
                <!-- <div class="volume">As of 11:26:28 Volume: 54.2M</div> -->
            </div>
            <div class="k-line-box">
                <!-- 标题 -->
                <!-- k线周期切换 -->
                <!-- <div class="select-kline-time-box">
                    <div class="show-time-list">
                        <div class="show-time-item" v-for="item in show_time" :key="item.id" :style="`background-color: ${ item.value == select_time ? 'var(--active-light-color)' : '#fff' }; color: ${ item.value == select_time ? 'var(--active-color)' : 'var(--text-color)' }`" @click.stop="clickChangeTime(item.value)">{{ item.shortName }}</div>
                    </div>
                    <div class="select-more-time-box" @click="show_more_time = true">
                        <div class="select-more-time" :style="`background-color: ${ select_time == select_more_time.value ? 'var(--active-light-color)' : '#fff' }; color: ${ select_time == select_more_time.value ? 'var(--active-color)' : 'var(--text-color)' }`">{{ select_more_time.shortName }}</div>
                        <div class="select-more-time-list" v-show="show_more_time">
                            <div class="select-more-time-item" v-for="item in select_time_list" :key="item.id" :style="`background-color: ${ item.value == select_time ? 'var(--active-more-light-color)' : '#fff' }; color: ${ item.value == select_time ? 'var(--active-color)' : 'var(--text-color)' }`" @click.stop="clickMoreTimeToChange(item)">{{ item.shortName }}</div>
                        </div>
                    </div>
                </div> -->
                <!-- k线图 -->
                <div id="kchart"></div>
                <!-- k线周期切换 -->
                <div class="select-kline-time-box">
                    <div class="show-time-list">
                        <div class="show-time-item" v-for="item in select_time_list" :key="item.id" :style="`background-color: ${ item.value == select_time ? 'var(--active-light-color)' : '#fff' }; color: ${ item.value == select_time ? 'var(--active-color)' : 'var(--text-color)' }`" @click.stop="clickChangeTime(item.value)">{{ item.shortName }}</div>
                    </div>
                </div>
                <!-- 开关高低 -->
                <div class="open-close-high-low">
                    <div class="item">
                        <div class="k">Open</div>
                        <!-- <div class="v">{{ stock_detail_data.more[1].v }}</div> -->
                        <div class="v">$0.00</div>
                    </div>
                    <div class="item">
                        <div class="k">Close</div>
                        <!-- <div class="v">{{ stock_detail_data.more[0].v }}</div> -->
                        <div class="v">$0.00</div>
                    </div>
                    <div class="item">
                        <div class="k">High</div>
                        <div class="v">$0.00</div>
                    </div>
                    <div class="item">
                        <div class="k">Low</div>
                        <div class="v">$0.00</div>
                    </div>
                </div>
            </div>
            <!-- <div class="info-line">
                <div class="card">
                    <div class="k">Market Cap</div>
                    <div class="v">{{ stock_detail_data.market_cap }}</div>
                </div>
                <div class="card">
                    <div class="k">Sector</div>
                    <div class="v">Technology</div>
                </div>
            </div> -->
        </div>
        <div class="footer">
            <div class="btn-box">
                <div class="btn" v-for="item in trade_type" @click="clickBuyOrSell(item)" :style="`background-color: ${ item.id == 1 ? 'var(--positive-number-color)' : ( market_status.close ? 'var(--negative-number-color)' : 'var(--text-light-color)' ) }`">
                    <div>{{ item.name }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { init, dispose } from 'klinecharts';
import TopTitleExit from '@/components/common/TopTitleExit.vue';
import { trade_type, openTradingSelector } from '@/service/trading.js';
import { stock_list, kline_data, chartDOM, changeStock, stock_detail_data, klinechart_reset, select_time, changeTime, market_status } from '@/service/market.js';
import { throttle, debounce } from '@/utils/debounce.js';
import { routerExit } from '@/utils/jump.js';
import { toast } from '@/service/status.js';

// const show_time = [
//     { id: 1, name: '1Mins', shortName: '1M', value: 60 * 1000 },
//     { id: 2, name: '5Mins', shortName: '5M', value: 5 * 60 * 1000 },
//     { id: 3, name: '15Mins', shortName: '15M', value: 15 * 60 * 1000 },
//     { id: 4, name: '30Mins', shortName: '30M', value: 30 * 60 * 1000 },
// ];

// const select_time_list = [
//     { id: 5, name: '1Hour', shortName: '1H', value: 60 * 60 * 1000 },
//     { id: 6, name: '1Day', shortName: '1D', value: 24 * 60 * 60 * 1000 },
//     { id: 7, name: '1Week', shortName: '1W', value: 7 * 24 * 60 * 60 * 1000 },
//     { id: 8, name: '1Month', shortName: '1Mon', value: 30 * 24 * 60 * 60 * 1000 },
// ];

const select_time_list = [
    { id: 1, name: '1Mins', shortName: '1M', value: 60 * 1000 },
    { id: 2, name: '5Mins', shortName: '5M', value: 5 * 60 * 1000 },
    { id: 3, name: '15Mins', shortName: '15M', value: 15 * 60 * 1000 },
    { id: 4, name: '30Mins', shortName: '30M', value: 30 * 60 * 1000 },
    { id: 5, name: '1Hour', shortName: '1H', value: 60 * 60 * 1000 },
    { id: 6, name: '1Day', shortName: '1D', value: 24 * 60 * 60 * 1000 },
    { id: 7, name: '1Week', shortName: '1W', value: 7 * 24 * 60 * 60 * 1000 },
    { id: 8, name: '1Month', shortName: '1Mon', value: 30 * 24 * 60 * 60 * 1000 },
];

// const select_more_time = ref(select_time_list[0]);

// const show_more_time = ref(false);

function clickBuyOrSell(item) {
    console.log(item);
    if (market_status.close == false && item.id == 2) {
        toast.warning('The market is closed. Please try again when the market reopens. ', 2500);
        return ;
    }
    openTradingSelector(item);
}

function clickChangeTime(time) {
    changeTime(time);
    show_more_time.value = false;
    select_more_time.value = select_time_list[0];
}

// function clickMoreTimeToChange(item) {
//     changeTime(item.value);
//     show_more_time.value = false;
//     select_more_time.value = item;
// }

// const active_time_name = computed(() => {
//     for (let i = 0; i < all_time.length; i++) {
//         if (all_time[i].value == select_time.value) {
//             return all_time[i].name;
//         }
//     }
// });

const klineStype = {
    candle: {
        tooltip: {
            // showRule: 'none',
            showRule: 'follow_cross',
            showType: 'rect',
            labels: ['time', 'open', 'close', 'high', 'low', 'volume'],
        }
    },
};

function initKLintChart() {
    // 初始化一个 k线图
    chartDOM.dom = init('kchart', klineStype);
    chartDOM.is_created = true;
    chartDOM.dom.setStyles(klineStype);
    chartDOM.dom.setBarSpace(5);
    chartDOM.dom.setOffsetRightDistance(40);
    chartDOM.dom.setTimezone('America/New_York');
    chartDOM.dom.createIndicator(
        {
            name: 'MA',
            shortName: 'MA',
            calcParams: [10, 20, 30],
            dragEnabled: true,
            plots: [
                { key: 'ma1', title: 'MA10: ', type: 'line' },
                { key: 'ma2', title: 'MA20: ', type: 'line' },
                { key: 'ma3', title: 'MA30: ', type: 'line' }
            ],
            regeneratePlots: (params) => {
                return params.map((p, i) => {
                    return { key: `ma${i + 1}`, title: `MA${p}: `, type: 'line' }
                })
            },
        },
        false,
        { id: "candle_pane", dragEnabled: true, height: 50 }
    );
    chartDOM.dom.applyNewData(kline_data.value, true);
}

watch(klinechart_reset, () => {
    // 解除监听器
    window.removeEventListener('resize', resize_kline);
    // 销毁 k线图
    dispose('kchart');
    chartDOM.is_created = false;
    // 初始化 k线图
    initKLintChart();
    // 重新绑定窗口大小监听器
    window.addEventListener('resize', resize_kline);
});

// 定义重绘函数
const resize_kline = debounce(() => {
    chartDOM.dom.resize();
}, 150);

onMounted(async () => {
    // 获取当前页面的 股票
    const urlParams = new URLSearchParams(window.location.search);
    const symbol = urlParams.get('symbol'); // 例如: 'AAPL.US'
    if (stock_detail_data.value.symbol != symbol) {
        for (let i = 0; i < stock_list.value.length; i++) {
            if (stock_list.value[i].symbol == symbol) {
                stock_detail_data.value = stock_list.value[i];
                changeStock(symbol);
                break;
            }
        }
    } else {
        // 等待 DOM 渲染完成
        await nextTick();
        // 初始化一个 k线图
        initKLintChart();
    }

    // // 等待 DOM 渲染完成
    // await nextTick();
    // // 初始化一个 k线图
    // chartDOM.dom = init('kchart');
    // chartDOM.dom.createIndicator(
    //     {
    //         name: 'MA',
    //         shortName: 'MA',
    //         calcParams: [10, 20, 30],
    //         dragEnabled: true,
    //         plots: [
    //             { key: 'ma1', title: 'MA10: ', type: 'line' },
    //             { key: 'ma2', title: 'MA20: ', type: 'line' },
    //             { key: 'ma3', title: 'MA30: ', type: 'line' }
    //         ],
    //         regeneratePlots: (params) => {
    //             return params.map((p, i) => {
    //                 return { key: `ma${i + 1}`, title: `MA${p}: `, type: 'line' }
    //             })
    //         },
    //     },
    //     true,
    //     { id: "candle_pane", dragEnabled: true }
    // );
    // console.log('k线初始化完成', chartDOM.dom);
    // // chartDOM.dom.setOffsetRightDistance(20);
    // chartRef.value = chartDOM.dom;
    // // 绘制 k线图 - 暴力解决
    // console.log('尝试绘制k线图');
    // initChart();
    // 在窗口尺寸改变时重绘 k线图
    window.addEventListener('resize', resize_kline);
});

onUnmounted(() => {
    // 解除监听器
    window.removeEventListener('resize', resize_kline);
    // 销毁 k线图
    dispose('kchart');
    // 销毁 k线图 DOM
    chartDOM.dom = null;
    chartDOM.is_created = false;
});
</script>

<style scoped lang="less">
.stock-detail {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: #fff;

    .body {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;

        .price-line {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2vw;

            .price {
                box-sizing: border-box;
                padding: 5vw;
                font-size: 4.5vw;
                font-weight: 700;
                text-align: center;
            }

            .change {
                font-size: 4vw;
            }

            .volume {
                font-size: 3.5vw;
                font-weight: 500;
                color: var(--text-color);
                // color: var(--text-light-color);
            }
        }

        .k-line-box {
            --h: 120vw;
            box-sizing: border-box;
            width: 100%;
            height: var(--h);
            padding: 5vw 2vw;

            .select-kline-time-box {
                display: flex;
                gap: 3vw;
                margin: 4vw 0;
                justify-content: center;

                .show-time-list {
                    display: flex;
                    gap: 3vw;
                    
                    .show-time-item {
                        font-size: 3vw;
                        padding: 0.5vw 1vw;
                        border-radius: 2vw;
                    }
                }

                .select-more-time-box {
                    position: relative;

                    &::after {
                        content: '';
                        display: block;
                        width: 0;
                        height: 0;
                        border-top: 1vw solid var(--text-color);
                        border-left: 1vw solid #00000000;
                        border-right: 1vw solid #00000000;
                        border-bottom: 1vw solid #00000000;
                        position: absolute;
                        top: 60%;
                        right: 1vw;
                        transform: translateY(-50%);
                    }

                    .select-more-time {
                        font-size: 3vw;
                        color: var(--text-color);
                        padding: 0.5vw 1vw;
                        padding-right: 3vw;
                        border-radius: 2vw;
                    }

                    .select-more-time-list {
                        position: absolute;
                        top: 101%;
                        left: 0;
                        z-index: 200;
                        box-shadow: 0 0 10vw rgba(0, 0, 0, 0.1);

                        .select-more-time-item {
                            font-size: 3vw;
                            padding: 2vw;
                            background-color: #fff;
                        }
                    }
                }
            }

            #kchart {
                width: 100%;
                height: var(--h);
            }

            .open-close-high-low {
                box-sizing: border-box;
                width: 90%;
                margin: 0 auto;
                padding: 3vw;
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                background-color: var(--bg-color);
                border-radius: 2vw;
                
                .item {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 1vw;

                    .k {
                        font-size: 3vw;
                        color: var(--text-light-color);
                    }

                    .v {
                        font-size: 3.5vw;
                    }
                }
            }
        }

        .info-line {
            width: 90%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 3.5vw;
            gap: 5vw;
            
            .card {
                box-sizing: border-box;
                flex: 1;
                padding: 4vw;
                border-radius: 3vw;
                background-color: var(--bg-color);

                .k {
                    font-size: 3.5vw;
                    color: var(--text-light-color);
                }

                .v {
                    font-size: 4.5vw;
                    font-weight: 600;
                    color: var(--text-color);
                }
            }
        }
    }
    
    .footer {
        box-sizing: border-box;
        position: sticky;
        left: 0;
        bottom: 0;
        padding: 4vw;
        // border-top: 0.1vw solid var(--border-color);

        .btn-box {
            width: 100%;
            display: flex;
            gap: 2vw;

            .btn {
                flex: 1;
                height: 10vw;
                border-radius: 1.5vw;
                display: flex;
                justify-content: center;
                align-items: center;

                &>div {
                    font-size: 3.5vw;
                    font-weight: 600;
                    color: #fff;
                }
            }

            .buy-btn {
                background-color: var(--active-color);
            }

            .sell-btn {
                background-color: var(--negative-number-color);
            }
        }
    }
}
</style>